import { EnhancedPlugins } from './enhanced-index';
import { Logger } from '../logger';

/**
 * 插件测试运行器
 */
export class PluginTestRunner {
  private plugins: EnhancedPlugins;

  constructor(plugins: EnhancedPlugins) {
    this.plugins = plugins;
  }

  /**
   * 运行所有插件测试
   */
  async runAllTests(): Promise<Record<string, any>> {
    const results: Record<string, any> = {};
    const allPlugins = this.plugins.getAllPlugins();

    Logger.info(`Starting tests for ${allPlugins.length} plugins`);

    for (const plugin of allPlugins) {
      const props = this.plugins.getPluginPropsById(plugin.pluginClass.ID);
      if (!props) continue;

      try {
        const testResult = await this.plugins.testPlugin(props.ID);
        results[props.ID] = testResult;
      } catch (error) {
        Logger.error(`Failed to test plugin ${props.ID}:`, error);
        results[props.ID] = {
          error: error instanceof Error ? error.message : String(error),
        };
      }
    }

    Logger.info('All plugin tests completed');
    return results;
  }

  /**
   * 运行特定类型插件的测试
   */
  async runTestsByType(type: number): Promise<Record<string, any>> {
    const results: Record<string, any> = {};
    const plugins = this.plugins.getPluginsByType(type);

    Logger.info(`Starting tests for ${plugins.length} plugins of type ${type}`);

    for (const plugin of plugins) {
      try {
        const testResult = await this.plugins.testPlugin(plugin.props.ID);
        results[plugin.props.ID] = testResult;
      } catch (error) {
        Logger.error(`Failed to test plugin ${plugin.props.ID}:`, error);
        results[plugin.props.ID] = {
          error: error instanceof Error ? error.message : String(error),
        };
      }
    }

    return results;
  }

  /**
   * 生成测试报告
   */
  generateTestReport(): string {
    const performanceReport = this.plugins.getPluginPerformanceReport();
    const timestamp = new Date().toISOString();

    const report = `
# ReadCat 插件测试报告
生成时间: ${timestamp}

## 总体统计
- 总插件数: ${performanceReport.lifecycle.totalPlugins}
- 已启用: ${performanceReport.lifecycle.states.enabled}
- 已禁用: ${performanceReport.lifecycle.states.disabled}
- 错误状态: ${performanceReport.lifecycle.states.error}
- 平均加载时间: ${performanceReport.lifecycle.averageLoadTime.toFixed(2)}ms
- 总错误数: ${performanceReport.lifecycle.totalErrors}

## 性能统计
${Object.entries(performanceReport.performance).map(([pluginId, stats]: [string, any]) => `
### ${pluginId}
- 总调用次数: ${stats.totalCalls}
- 平均执行时间: ${stats.averageExecutionTime.toFixed(2)}ms
- 成功率: ${(stats.successRate * 100).toFixed(2)}%
- 最慢方法: ${stats.slowestMethod || 'N/A'}
- 最快方法: ${stats.fastestMethod || 'N/A'}
- 错误次数: ${stats.errorCount}
`).join('')}

## 测试结果
${Object.entries(performanceReport.testResults).map(([pluginId, result]: [string, any]) => `
### ${pluginId}
- 测试总数: ${result.totalTests}
- 通过: ${result.passedTests}
- 失败: ${result.failedTests}
- 耗时: ${result.duration}ms
`).join('')}
`;

    return report;
  }
}